<?php

namespace App\Http\Controllers\Company;

use App\Facades\CustomPassword;
use App\Http\Requests\Common\Captcha\SmsCodeRequest;
use App\Http\Requests\Company\Register\OrdinaryRegisterRequest;
use App\Jobs\CompanyRegisterEmail;
use App\Models\Company\CompanyLoginRecord;
use App\Models\Company\CompanyVisitRecord;
use Illuminate\Http\Request;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyUser;
use App\Http\Requests\Company\Register\CompanyBasicRequest;
use Style, Site, Sms;


class RegisterController extends CommonController{
    public function index(){
        return Style::view('company.auth.register');
    }

    /**
     * 分帧地图
     * @return mixed
     */
    public function iframeMap(){
        return Style::view('company.iframeMap');
    }

    /**
     * ajax验证用户名
     * @param Request $request
     */
    public function ajaxUsername(Request $request){
        $username = $request->input('username');
        $result = CompanyUser::where('username', $username)->first();
        //判断用户名是不是被注册
        echo ($result) ? 'false' : 'true';
    }

    /**
     * 企业基本信息注册
     * @return mixed
     */
    public function registerBasic(){
        $userInfo = auth()->guard('company')->user();
        $phone = ($userInfo->phone) ? explode('-', $userInfo->phone) : [];
        return Style::view('company.registerBasic', compact('userInfo', 'phone'));
    }

    /**
     * ajax验证手机号码
     * @param Request $request
     */
    public function ajaxMobile(Request $request){
        $mobile = $request->input('mobile');
        $result = CompanyUser::where('mobile', $mobile)->first();
        //判断手机不是被注册
        echo ($result) ? 'false' : 'true';
    }

    /**
     * 企业注册post
     * @param CompanyBasicRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function postRegisterBasic(CompanyBasicRequest $request){
        $input = $request->only('company_name', 'brands', 'comkind', 'industry', 'established', 'employee_num', 'temptation', 'profile',
            'contacts', 'mobile', 'phone', 'fax', 'email', 'qq', 'region', 'address', 'longitude', 'latitude', 'coordinate_address', 'website', 'lines');
        $phone = trim($request->input('area_code')) . '-' . trim($request->input('phone'));
        $phone .= trim($request->input('ext')) ? "-" . trim($request->input('ext')) : '';
        $phone = trim($phone, '-');

        //获取用户信息ID
        $userInfo = auth()->guard('company')->user();
        $input['uid'] = $userInfo->uid;
        $input['phone'] = $phone;
        $input['addtime'] = date('Y-m-d H:i:s', time());
        $input['updatetime'] = date('Y-m-d H:i:s', time());

        $companyBasic = CompanyBasic::where('uid', $userInfo->uid)->count();
        if(empty($companyBasic)){
            //return Style::view('errors.404', ['exception' => '企业基本信息已经注册...'], 404);
            CompanyBasic::create($input);
        }
        return redirect('company/welcome');
    }

    /**
     * 获取短信验证码
     * @param SmsCodeRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxMobCode(SmsCodeRequest $request){
        $mobileNum = $request->input('mobile');
        $result = CompanyUser::where('mobile', $mobileNum)->orWhere('username', $mobileNum)->first();
        if($result){
            return response()->json(['status' => '2', 'msg' => '此手机号码已经注册']);
        }else{
            //设置session
            $request->session()->put('mobile_verification_code', rand(1000, 9999));
            $request->session()->put('mobile_verification', $mobileNum);
            //模板参数
            $smsParam = array(
                'product' => Site::get('webname'),
                'code' => (string)session('mobile_verification_code')
            );
            $sendResult = Sms::codeSend($mobileNum, $smsParam);
            //返回对象
            if(is_object(@$sendResult->result) && $sendResult->result->err_code == '0'){
                return response()->json(['status' => '1', 'msg' => '发送短信成功']);
            }else{
                return response()->json(['status' => '0', 'msg' => '一分钟之内只能发一次,或者您发送的次数已经达到上限']);
            }
        }
    }

    //---普通模式注册--------------------------------------------------------------------------------------------
    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function getOrdinaryRegister(Request $request){
        return Style::view('company.auth.ordinaryRegister');
    }

    /**
     * 普通模式注册提交
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postOrdinaryRegister(OrdinaryRegisterRequest $request){
        //防企业注册配置每天注册的个数（默认20个）
        $ipCount = CompanyUser::where('regip', getIp())->where('regtime','>=',date('Y-m-d H:i:s',strtotime('-1 days')))->count();
        if($ipCount >= Site::get('companyReg')){
            return redirect()->back()->with('err','注册失败，请联系客服');
        }

        $input = $request->only('username', 'password', 'contacts', 'company_name', 'email', 'phone',
            'last_login_ip', 'regtime', 'updatetime', 'last_login_time');
        $input['password'] = CustomPassword::make($input['password']);
        $input['regtime'] = date('Y-m-d H:i:s', time());
        $input['updatetime'] = date('Y-m-d H:i:s', time());
        $input['regip'] = getIp();
        $input['last_login_ip'] = getIp();
        $input['last_login_time'] = date('Y-m-d H:i:s', time());
        $input['phone'] = $request->area_code . '-' . $request->phone . '-' . $request->ext;
        $insert_id = CompanyUser::insertGetId($input);
        //登录用户信息
        auth()->guard('company')->loginUsingId($insert_id);
        $user = auth()->guard('company')->user();
        //注册记录表
        $record = array();
        $record['uid'] = $user->uid;
        $record['company_login_ip'] = getIp();
        $record['company_login_time'] = date('Y-m-d H:i:s', time());
        $record['login_type'] = 1;
        $record['type'] = 1;
        //登录记录表和突访记录表
        CompanyLoginRecord::create($record);
        CompanyVisitRecord::create($record);

        //判断是邮箱是不是存在
        if(!empty($request->email)){
            $user = auth()->guard('company')->user();
            $userInfo = (object)null;
            $userInfo->uid = $user->uid;
            $userInfo->email = $user->email;
            $userInfo->username = $user->username;
            $userInfo->password = $request->password;
            //添加到队列中
            $this->dispatch(new CompanyRegisterEmail($userInfo));
        }
        return redirect("company/register_basic");
    }
}
